package it.unipd.dei.project.iandroid;

import java.io.IOException;

import android.app.Activity;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Matrix;
import android.media.ExifInterface;
import android.os.Bundle;
import android.widget.ImageView;

public class Picture extends Activity {

	ImageView iw;
	Cursor cur;
	DatabaseOpenHelper db;
	SQLiteDatabase base;
	Bitmap image;
	Bitmap image_to_upload;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_picture);
		db = new DatabaseOpenHelper(this);
		base = db.getWritableDatabase();

		iw = (ImageView) findViewById(R.id.foto);

		Intent intent = getIntent();
		String pkg = getPackageName();
		int position = intent.getIntExtra(pkg + "position", -1);
		int idPartita = intent.getIntExtra("id", -1);
		cur = base.query("Foto", null, "IdPartita=" + idPartita, null, null, null, "Id ASC");

		for (int i = 0; i < cur.getCount(); i++) {
			cur.moveToNext();
			if (position == (i)) {
				BitmapFactory.Options bfOptions = new BitmapFactory.Options();

				bfOptions.inDither = false;
				bfOptions.inPurgeable = true;
				bfOptions.inInputShareable = true;
				bfOptions.inSampleSize = 2;
				
				ExifInterface exif = null;
				try {
					exif = new ExifInterface(cur.getString(2));
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
				int orientation = exif.getAttributeInt(ExifInterface.TAG_ORIENTATION, ExifInterface.ORIENTATION_NORMAL);
				image = BitmapFactory.decodeFile(cur.getString(2), bfOptions);
				
				Matrix mat = new Matrix();
				switch (orientation){
				case ExifInterface.ORIENTATION_ROTATE_270:
					mat.postRotate(270);
					image_to_upload = Bitmap.createBitmap(image, 0, 0, image.getWidth(), image.getHeight(), mat, true);
					iw.setImageBitmap(image_to_upload);
					break;
				
				case ExifInterface.ORIENTATION_ROTATE_180:
					mat.postRotate(180);
					image_to_upload = Bitmap.createBitmap(image, 0, 0, image.getWidth(), image.getHeight(), mat, true);
					iw.setImageBitmap(image_to_upload);
					break;
					
				case ExifInterface.ORIENTATION_ROTATE_90:
					mat.postRotate(90);
					image_to_upload = Bitmap.createBitmap(image, 0, 0, image.getWidth(), image.getHeight(), mat, true);
					iw.setImageBitmap(image_to_upload);
					break;
				case ExifInterface.ORIENTATION_NORMAL:
					mat.postRotate(0);
					image_to_upload = Bitmap.createBitmap(image, 0, 0, image.getWidth(), image.getHeight(), mat, true);
					iw.setImageBitmap(image_to_upload);
					break;
				}
					
			}
		}
		cur.close();
		base.close();
		db.close();
	}

}
